package normal

import (
    "crypto/md5"
    "encoding/hex"
    "math/rand"
    "time"
    "runtime"
    "strings"
    "os"
    "fmt"
    "bytes"
    "sync"
    "net/http"
    "encoding/json"
    "github.com/Tang-RoseChild/mahonia"
)

// 生成长度为length的随机字符串
func RandString(length int64) string {
    sources := []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    result := []byte{}
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    sourceLength := len(sources)
    var i int64 = 0
    for ; i < length; i++ {
        result = append(result, sources[r.Intn(sourceLength)])
    }

    return string(result)
}

// 生成32位MD5摘要
func Md5(str string) string {
    m := md5.New()
    m.Write([]byte(str))

    return hex.EncodeToString(m.Sum(nil))
}

// 生成0-max之间随机数
func RandNumber(max int) int {
    r := rand.New(rand.NewSource(time.Now().UnixNano()))

    return r.Intn(max)
}

// 判断当前系统是否是windows
func IsWindows() bool {
    return runtime.GOOS == "windows"
}

// 批量替换字符串
func ReplaceStrings(s string, old []string, replace []string) string  {
    if s == "" {
        return s
    }
    if len(old) != len(replace) {
        return s
    }

    for i, v := range old {
        s = strings.Replace(s, v, replace[i], 1000)
    }

    return s
}

func InStringSlice(slice []string, element string) bool {
    element = strings.TrimSpace(element)
    for _, v := range slice {
        if strings.TrimSpace(v) == element{
            return true
        }
    }

    return false
}
// GBK编码转换为UTF8
func GBK2UTF8(s string) (string, bool) {
    dec := mahonia.NewDecoder("gbk")

    return dec.ConvertStringOK(s)
}
// 转义json特殊字符
func EscapeJson(s string) string  {
    specialChars := []string{"\\", "\b","\f", "\n", "\r", "\t", "\"",}
    replaceChars := []string{ "\\\\", "\\b", "\\f", "\\n", "\\r", "\\t", "\\\"",}

    return ReplaceStrings(s, specialChars, replaceChars)
}

// 判断文件是否存在及是否有权限访问
func FileExist(file string) bool {
    _, err := os.Stat(file)
    if os.IsNotExist(err) {
        return false
    }
    if os.IsPermission(err) {
        return false
    }

    return true
}

// 格式化环境变量
func FormatUnixEnv(key, value string) string {
    return fmt.Sprintf("export %s=%s; ", key, value)
}
//字符串凭借
func StringJoin(arg ...string) string {
    b := bytes.Buffer{}
    for _,value:=range arg {
        b.WriteString(value)
    }
    return b.String()
    
}
//任务队列
func DoListLimit(data *[]interface{},b func(interface{},int,*sync.Mutex),count int,all int)  {

    m:=new (sync.Mutex)
    datacount:=0
    if all>len(*data) {
        datacount=len(*data)
    }else {
        datacount=all
    }
    ch:=make(chan int)
    chcount := count
    for i:=0;i<datacount;{
        if i+count>datacount{
            chcount=datacount-i
        }
        for h:=0;h<chcount;h++{
            go func(one interface{},index int,m *sync.Mutex) {
                b(one,index,m)
                ch<-0
            }((*data)[i],i,m)
            i++
        }
        for j:=0;j<chcount;j++{
            <-ch
        }
    }

}
// post 网络请求 ,params 是url.Values类型
func Post(apiURL string, param interface{},try int)(*http.Response, error){
    jsonbyte,err := json.Marshal(param)
    if err != nil {
        return nil,err
    }
    req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonbyte))
    req.Header.Set("X-Custom-Header", "loan_data")
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    client.Timeout=time.Second*10
    resp, err := client.Do(req)
    if err != nil {
        return nil,err;
    }
    if resp.StatusCode!=http.StatusOK{
        for i:=0;i<try ;i++  {
            resp, err := client.Do(req)
            if err != nil && resp.StatusCode==http.StatusOK{
                break
            }

        }
    }
    defer resp.Body.Close()
    return resp,err

}
func Filter_phone(num string) string{
    var tmp_sr []rune=make([]rune,len(num))
    index:=0
    for _,v:=range num {
        switch v {
        case ' ':
        case '-':
        case '+':
            continue
            break
        default:
            tmp_sr[index]=v
            index++
        }
    }
    for index1,v:=range tmp_sr {
        if v=='1'{
            if len(tmp_sr[index1:index])==11 {
                return string(tmp_sr[index1:index])
            }
            if len(tmp_sr)>4 {
                if string(tmp_sr[0:2]) == "86" {
                    return string(tmp_sr[2:index])
                }
                if string(tmp_sr[0:4]) == "0086" {
                    return string(tmp_sr[4:index])
                }
            }
            break
        }

    }
    return string(tmp_sr[:index])

}
